import type Typings from "@/typings";

// 时间格式化
export const timeFormat: (date: number, format: string) => string = (
  date,
  format = "yyyy-MM-dd HH:mm:ss"
) => {
  const t = new Date(Number(date));
  const map: Typings.Common.plainObj = {
    yyyy: t.getFullYear(),
    MM: String(t.getMonth() + 1).padStart(2, "0"), // 月份从0开始，所以要加1
    dd: String(t.getDate()).padStart(2, "0"),
    HH: String(t.getHours()).padStart(2, "0"),
    mm: String(t.getMinutes()).padStart(2, "0"),
    ss: String(t.getSeconds()).padStart(2, "0"),
  };

  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match) => map[match]);
};

// 延迟等待
export const sleep: (delay: number) => Promise<boolean> = (delay = 1000) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, delay);
  });
};

// 是否为开发环境
export const isDev: boolean = import.meta.env.MODE === "development";

// 数组匹配
export const transform: (
  code: Typings.Common.normalValue,
  options: Typings.Common.option[]
) => string = (code = "", options = []) => {
  return options.find((i) => i.code === code)?.name || "--";
};

// 返回指定日期的开始时间|结束时间
export const getTimeFromDate: (
  t: number | string,
  type: "start" | "end"
) => number = (t, type = "start") => {
  const date = new Date(t);
  const y = date.getFullYear();
  const m = date.getMonth();
  const d = date.getDate();

  const newDate =
    type === "start"
      ? new Date(y, m, d, 0, 0, 0)
      : new Date(y, m, d, 23, 59, 59);

  return newDate.getTime();
};
